﻿using FieldTools.MediaFindOut.Control;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Runtime.CompilerServices;
using System.Windows;

namespace FieldTools.MediaFindOut
{
    /// <summary>
    /// ListShowWindow.xaml 的交互逻辑
    /// </summary>
    public partial class FileListShowWindow : Window
    {
        #region 初始化
        /// <summary>
        /// 默认构造，自带示例数据
        /// </summary>
        public FileListShowWindow()
        {
            List<string> files = ["./Assets/Videos/m1.mp4", "./Assets/Videos/m2.mp4", "./Assets/Videos/m3.mp4"];
            Init(files);
            InitializeComponent();
            this.DataContext = this;
        }
        /// <summary>
        /// 使用文件路径集合初始化
        /// </summary>
        /// <param name="files"></param>
        public FileListShowWindow(List<string> files)
        {
            Init(files);
            InitializeComponent();
            this.DataContext = this;
        }
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="files"></param>
        private void Init(List<string> files)
        {
            //Files = [];
            FileInfos = [];
            foreach (var item in files)
            {
                var fullPath = System.IO.Path.GetFullPath(item);
                if (!string.IsNullOrEmpty(fullPath) && File.Exists(fullPath))
                {
                    FileInfo fileInfo = new(fullPath);
                    //Files.Add(fileInfo);
                    FileInfos.Add(new()
                    {
                        Name = fileInfo.Name,
                        FullName = fileInfo.FullName,
                        Length = fileInfo.Length,
                        CreationTime = fileInfo.CreationTime,
                        LastAccessTime = fileInfo.LastAccessTime,
                        LastWriteTime = fileInfo.LastWriteTime,
                    });
                    //var json = JsonSerializer.Serialize(fileInfo);
                    //if (!string.IsNullOrEmpty(json))
                    //{
                    //    var myFileInfo = JsonSerializer.Deserialize<MyFileInfo>(json);
                    //    if (myFileInfo != null)
                    //    {
                    //        FileInfos.Add(myFileInfo);
                    //    }

                    //}
                }
            }
        }
        #endregion

        #region 实体
        /// <summary>
        /// 文件列表
        /// </summary>
        public List<MyFileInfo> FileInfos { get; set; } = [];
        /// <summary>
        /// 选中的条目
        /// </summary>
        public MyFileInfo SelectFielInfo
        {
            get { return (MyFileInfo)GetValue(SelectFielInfoProperty); }
            set { SetValue(SelectFielInfoProperty, value); }
        }
        /// <summary>
        /// Using a DependencyProperty as the backing store for SelectFielInfo.  This enables animation, styling, binding, etc...
        /// </summary>
        public static readonly DependencyProperty SelectFielInfoProperty =
            DependencyProperty.Register("SelectFielInfo", typeof(MyFileInfo), typeof(FileListShowWindow), new PropertyMetadata(new MyFileInfo()));
        /// <summary>
        /// 导出为txt目录
        /// </summary>
        public bool IsOutToTxt
        {
            get { return (bool)GetValue(IsOutToTxtProperty); }
            set { SetValue(IsOutToTxtProperty, value); }
        }
        /// <summary>
        /// Using a DependencyProperty as the backing store for IsOutToTxt.  This enables animation, styling, binding, etc...
        /// </summary>
        public static readonly DependencyProperty IsOutToTxtProperty =
            DependencyProperty.Register("IsOutToTxt", typeof(bool), typeof(FileListShowWindow), new PropertyMetadata(false));
        /// <summary>
        /// 导出复制
        /// </summary>
        public bool IsOutCopyFiles
        {
            get { return (bool)GetValue(IsOutCopyFilesProperty); }
            set { SetValue(IsOutCopyFilesProperty, value); }
        }
        /// <summary>
        /// Using a DependencyProperty as the backing store for IsOutCopyFiles.  This enables animation, styling, binding, etc...
        /// </summary>
        public static readonly DependencyProperty IsOutCopyFilesProperty =
            DependencyProperty.Register("IsOutCopyFiles", typeof(bool), typeof(FileListShowWindow), new PropertyMetadata(false));
        #endregion

        #region 事件
        /// <summary>
        /// 导出所有
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuItem_OutPutAll_Click(object sender, RoutedEventArgs e)
        {
            var outPath = MainWindow.SelectFolder();
            if (outPath == null) return;
            if (IsOutToTxt)
            {
                var filePath = outPath + "资源路径集合导出" + DateTime.Now.Ticks + ".txt";
                if (!File.Exists(filePath))
                {
                    var st = File.Create(filePath);
                    //所有的流使用后记得都要关闭，不然会出现占用的情况
                    st.Close();
                }
                var contentStr = "";
                FileInfos.ForEach(x => { contentStr += x + "\r\n"; });
                File.WriteAllTextAsync(filePath, contentStr).Wait();
                MessageManage.Success($"目录创建并写入完成，文件路径为{filePath}");
                //System.Diagnostics.Process.Start(filePath);
            }
            if (IsOutCopyFiles)
            {
                foreach (var item in FileInfos)
                {
                    if (File.Exists(item.FullName) && Directory.Exists(outPath))
                    {
                        MainWindow.SaveAsFile(item.FullName, outPath);
                        MessageManage.Success($"导出完成，输出目录为{outPath}");
                        //System.Diagnostics.Process.Start(outPath);
                    }
                }
            }

        }
        /// <summary>
        /// 导出选中项
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuItem_OutPutSelect_Click(object sender, RoutedEventArgs e)
        {
            var outPath = MainWindow.SelectFolder();
            if (outPath == null) return;
            if (IsOutToTxt)
            {
                var filePath = outPath + "资源路径集合导出" + DateTime.Now.Ticks + ".txt";
                if (!File.Exists(filePath))
                {
                    File.Create(filePath).Close();
                    //所有的流使用后记得都要关闭，不然会出现占用的情况
                }
                var contentStr = "";
                FileInfos.ForEach(x => { if (x.IsChecked) contentStr += x + "\r\n"; });
                File.WriteAllTextAsync(filePath, contentStr).Wait();
                MessageManage.Success($"导出完成，文件路径为{filePath}");
                //System.Diagnostics.Process.Start(filePath);
            }
            if (IsOutCopyFiles)
            {
                foreach (var item in FileInfos)
                {
                    if (File.Exists(item.FullName) && item.IsChecked && Directory.Exists(outPath))
                    {
                        MainWindow.SaveAsFile(item.FullName, outPath);
                        MessageManage.Success($"导出完成，输出目录为{outPath}");
                        //System.Diagnostics.Process.Start(outPath);
                    }
                }
            }
        }
        /// <summary>
        /// 在文件浏览器中打开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuItem_OpenInFloder_Click(object sender, RoutedEventArgs e)
        {
            if (SelectFielInfo != null)
            {
                System.Diagnostics.Process.Start("Explorer", "/select," + SelectFielInfo.FullName);
            }
        }
        /// <summary>
        /// 表格被选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DataGrid_Selected(object sender, RoutedEventArgs e)
        {
            openInFloderItem.IsEnabled = true;
        }
        #endregion
    }

    /// <summary>
    /// 自定义文件信息
    /// </summary>
    public class MyFileInfo : INotifyPropertyChanged
    {
        /// <summary>
        /// 属性改变
        /// </summary>
        public event PropertyChangedEventHandler? PropertyChanged;

        private void RaisePropertyChanged([CallerMemberName] string propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        private bool isChecked = false;
        /// <summary>
        /// 是否选中
        /// </summary>
        public bool IsChecked
        {
            get { return isChecked; }
            set { isChecked = value; RaisePropertyChanged(); }
        }

        private string name = "";
        /// <summary>
        /// 名称
        /// </summary>
        public string Name
        {
            get { return name; }
            set { name = value; RaisePropertyChanged(); }
        }
        private string fullName = "";
        /// <summary>
        /// 完整路径
        /// </summary>
        public string FullName
        {
            get { return fullName; }
            set { fullName = value; RaisePropertyChanged(); }
        }

        private long length;
        /// <summary>
        /// 文件长度
        /// </summary>
        public long Length
        {
            get { return length; }
            set { length = value; RaisePropertyChanged(); }
        }

        private DateTime creationTime = DateTime.Parse("1970/01/01 00:00:00");
        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime CreationTime
        {
            get { return creationTime; }
            set { creationTime = value; RaisePropertyChanged(); }
        }

        private DateTime lastAccessTime;
        /// <summary>
        /// 最后访问时间
        /// </summary>
        public DateTime LastAccessTime
        {
            get { return lastAccessTime; }
            set { lastAccessTime = value; RaisePropertyChanged(); }
        }

        private DateTime lastWriteTime;
        /// <summary>
        /// 最后修改时间
        /// </summary>
        public DateTime LastWriteTime
        {
            get { return lastWriteTime; }
            set { lastWriteTime = value; RaisePropertyChanged(); }
        }

    }
}
